#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :demo_12306_buy.py
# @Time      :2021/7/29 10:57
# @author    :Harry
'''
@case : 12306 预订票
@step:
1、访问12306网站；
2、首页查询票信息；
3、预订
4、退出
'''
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.maximize_window()
# 1、访问12306网站；
driver.get('https://www.12306.cn/index/index.html')
time.sleep(3)

# 2、首页查询票信息；
driver.find_element_by_id('fromStationText').click()            # 清除默认值
driver.find_element_by_id('fromStationText').send_keys('成都')   # 出发点
driver.find_element_by_id('fromStationText').send_keys(Keys.ARROW_DOWN)  # 模拟键盘 向下键
driver.find_element_by_id('fromStationText').send_keys(Keys.ARROW_DOWN)  # 模拟键盘 回车键
driver.find_element_by_id('fromStationText').send_keys(Keys.ENTER)

time.sleep(1)
driver.find_element_by_id('toStationText').click()              # 清除默认值
driver.find_element_by_id('toStationText').send_keys('上海虹桥')     # 目的地
# driver.find_element_by_id('toStationText').send_keys(Keys.ARROW_DOWN)  # 模拟键盘 向下键
driver.find_element_by_id('toStationText').send_keys(Keys.ENTER)       # 模拟键盘 回车键

time.sleep(1)
js = "document.getElementById('train_date').removeAttribute('readonly')"
driver.execute_script(js)

driver.find_element_by_id('train_date').clear()
driver.find_element_by_id('train_date').send_keys('2021-08-08')
driver.find_element_by_id('train_date').click()
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div[1]/div/div[2]/div[1]/div[1]/div[2]/label').click()

time.sleep(2)
driver.find_element_by_id('search_one').click()         # 查询

# 3、预订
handles = driver.window_handles
driver.switch_to.window(handles[-1])   # 切换窗口
driver.find_element_by_id('qd_closeDefaultWarningWindowDialog_id').click()
time.sleep(3)
driver.find_element_by_xpath('//td[contains(@id,"D2208")]').click()
time.sleep(2)
driver.find_element_by_xpath('//a[contains(@onclick,"D2208") and text()="预订"]').click()

# 4、退出
time.sleep(3)
driver.quit()